package com.hs.demos.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

public class DatePreciseAlgorithm implements StandardShardingAlgorithm<LocalDateTime> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<LocalDateTime> rangeShardingValue) {
        List<String> list = new ArrayList<>();
        Range<LocalDateTime> valueRange = rangeShardingValue.getValueRange();
        LocalDate lowerLocalDate = valueRange.lowerEndpoint().toLocalDate();
        LocalDate upperLocalDate = valueRange.upperEndpoint().toLocalDate();
        if (lowerLocalDate.equals(upperLocalDate)) {
            addTableName(list, rangeShardingValue, collection, lowerLocalDate);
        } else {
            while (lowerLocalDate.isBefore(upperLocalDate)) {
                addTableName(list, rangeShardingValue, collection, lowerLocalDate);
                lowerLocalDate = lowerLocalDate.plusMonths(1);
            }
        }
        return list;
    }

    private void addTableName(List<String> list, RangeShardingValue<LocalDateTime> rangeShardingValue, Collection<String> collection, LocalDate localDate) {
        String tableName = rangeShardingValue.getLogicTableName() + "_" + localDate.getYear() + "_" + localDate.getMonthValue();
        if (collection.contains(tableName)) {
            list.add(tableName);
        } else {
            //创建表
            throw new IllegalArgumentException("未找到匹配的数据表");
        }
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<LocalDateTime> preciseShardingValue) {
        LocalDateTime value = preciseShardingValue.getValue();
        String tableName = preciseShardingValue.getLogicTableName() + "_" + value.getYear() + "_" + value.getMonthValue();
        if (collection.contains(tableName)) {
            return tableName;
        } else {
            throw new IllegalArgumentException("未找到匹配的数据表");
        }
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
